﻿using System.IO;
using System.Windows.Input;
using Bulb.Core.Services.CollectionService;
using Bulb.Core.Services.DataStore;
using Cirrious.MvvmCross.Plugins.File;
using Cirrious.MvvmCross.Plugins.PictureChooser;
using Cirrious.MvvmCross.ViewModels;

namespace Bulb.Core.ViewModels
{
    public class EditBulbViewModel : BulbViewModel
    {
        public EditBulbViewModel(ICollectionService collectionService, IMvxPictureChooserTask pictureChooserTask, IMvxFileStore fileStore) 
            : base(collectionService, pictureChooserTask, fileStore)
        {
        }

        public class Nav
        {
            public int Id { get; set; }
        }

        public void Init(Nav navigation)
        {
            Item = CollectionService.Get(navigation.Id);
            MakeItVisible = Item.ImagePath != null;
        }

        private BulbItem _item;
        public BulbItem Item
        {
            get { return _item; }
            set
            {
                _item = value;
                RaisePropertyChanged(() => Item);
            }
        }

        public MvxCommand CancelCommand
        {
            get { return new MvxCommand(() => { DeleteTemp(); Close(this); }); }
        }

        private MvxCommand _updateCommand;
        public ICommand UpdateCommand
        {
            get
            {
                _updateCommand = _updateCommand ?? new MvxCommand(DoUpdate);
                DeleteTemp();
                return _updateCommand;
            }
        }

        private void DoUpdate()
        {
            if (!Validate(Item.Name))
                return;

            if (PictureBytes != null)
                Item.ImagePath = GenerateImagePath(ImagePath);
            
            if (!MakeItVisible && Item.ImagePath != null)
            {
                FileStore.DeleteFile(Item.ImagePath);
                Item.ImagePath = null;
            }
           
            CollectionService.Update(Item);
            Close(this);
        }

        protected override void PictureAvailable(Stream stream)
        {
            base.PictureAvailable(stream);

            Item.ImagePath = GenerateImagePath("Temp");
            RaisePropertyChanged(() => Item);
        }
    }
}
